package org.looop.studio.bean.builder.impl;

import java.lang.reflect.InvocationTargetException;

import org.looop.studio.bean.builder.BeanBuilder;
import org.looop.studio.bean.desc.ValueDesc;
import org.looop.studio.bean.domain.BeanDefinition;
import org.looop.studio.bean.factory.BeanFactory;
import org.looop.studio.bean.util.BeanFactoryUtil;

public class ConstructorBuilder implements BeanBuilder {

	@Override
	public Object buildBean(BeanFactory beanFactory,
			BeanDefinition beanDefinition) throws InstantiationException,
			IllegalAccessException, ClassNotFoundException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException {
		ValueDesc[] constructorArgs = beanDefinition.getConstructorArgs();
		if(constructorArgs == null){
			return BeanFactoryUtil.getInstance(beanDefinition.getClazz());
		}
		Object[] constructorParameters = new Object[constructorArgs.length];
		for(int i=0; i < constructorArgs.length; i++){
			constructorParameters[i] = constructorArgs[i].getValue(beanFactory);
		}
		return BeanFactoryUtil.getInstance(beanDefinition.getClazz(), constructorParameters);
	}

}
